#pragma once

#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <functional>
#include <memory>

#include "InetAddr.hpp"
#include "Log.hpp"

/*
对socket进行封装，先创建一个基类，后面用继承多态来区分实现TcpSocket和UdpSocket
*/
namespace socket_ns
{

	class Socket;
	enum
	{
		SOCKET_ERROR = 1,
		BIND_ERROR,
		LISTEN_ERROR,
		USAGE_ERROR,
		ACCEPT_ERROR
	};

	const static int d_backlog = 16; // 设置连接的个数

	using socket_sptr = std::shared_ptr<Socket>;

	class Socket
	{
	public:
		virtual void CreateSocketOrDie() = 0;			  // 创建socket文件描述符
		virtual void BindSocketOrDie(InetAddr &addr) = 0; // 绑定端口号
		virtual void ListenSocketOrDie() = 0;			  // 监听
		virtual socket_sptr Accepter(InetAddr *addr) = 0; // 请求
		virtual bool Connetcor(InetAddr &addr) = 0;		  // 连接
		virtual int SockFd() = 0;						  // 获取socket
		virtual void SetSocketAddrReuse() = 0;			  // 设置套接字复用

		virtual ssize_t Recv(std::string *out) = 0;
		virtual int Send(const std::string &in) = 0;
		virtual int Close() = 0;
		// 多态
	public:
		void BuildListenSocket(InetAddr &addr)
		{
			CreateSocketOrDie();
			SetSocketAddrReuse();
			BindSocketOrDie(addr);
			ListenSocketOrDie();
		}
		bool BuildClientSocket(InetAddr &addr)
		{
			CreateSocketOrDie();
			return Connetcor(addr);
		}

	private:
		int _sockfd; // socket文件描述符
	};

	class TcpSocket : public Socket
	{
	public:
		TcpSocket(int fd = -1) : _sockfd(fd)
		{
		}

		void CreateSocketOrDie() override
		{
			// 1.创建字符流式套接字
			_sockfd = socket(AF_INET, SOCK_STREAM, 0);
			if (_sockfd < 0)
			{
				LOG(FATAL, "TcpSocket error");
				exit(SOCKET_ERROR);
			}

			LOG(DEBUG, "TcpSocket create success, sockfd is : %d\n", _sockfd);
		}

		void BindSocketOrDie(InetAddr &addr) override
		{
			// 2.bind
			// 先填充socket_in结构
			struct sockaddr_in saddr;
			memset(&saddr, 0, sizeof(saddr));
			saddr.sin_family = AF_INET;
			saddr.sin_port = htons(addr.port());
			saddr.sin_addr.s_addr = inet_addr(addr.ip().c_str());

			int r = ::bind(_sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
			if (r < 0)
			{
				LOG(FATAL, "Tcp_bind error");
				exit(BIND_ERROR);
			}

			LOG(DEBUG, "Tcp_bind success, sockfd is : %d\n", _sockfd);
		}

		void ListenSocketOrDie() override
		{
			int r = ::listen(_sockfd, d_backlog);
			if (r < 0)
			{
				LOG(FATAL, "listen error");
				exit(LISTEN_ERROR);
			}

			LOG(DEBUG, "listen success, sockfd is : %d\n", _sockfd);
		}

		socket_sptr Accepter(InetAddr *addr) override // 输出参数
		{
			struct sockaddr_in peer;
			socklen_t len = sizeof(peer);
			int sockfd = ::accept(_sockfd, (struct sockaddr *)&peer, &len); // 请求，获取到服务器信息
			if (sockfd < 0)
			{
				LOG(WARNING, "accept error\n");
				return nullptr;
			}

			*addr = peer;
			socket_sptr sock = std::make_shared<TcpSocket>(sockfd);
			return sock; // 这里给出的是要通信的文件描述符
		}

		bool Connetcor(InetAddr &addr) override // 一般给client用的
		{
			struct sockaddr_in server;
			// 构建目标主机的socket信息
			memset(&server, 0, sizeof(server));
			server.sin_family = AF_INET;
			server.sin_port = htons(addr.port());
			server.sin_addr.s_addr = inet_addr(addr.ip().c_str());

			int r = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
			if (r < 0)
			{
				std::cerr << "connect error" << std::endl;
				return false;
			}

			std::cerr << "connect success" << std::endl;
			return true;
		}

		void SetSocketAddrReuse() override // 设置套接字复用
		{
			int opt = 1;
			::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
		}

		ssize_t Recv(std::string *out) override
		{
			char buffer[1024];
			ssize_t n = recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
			if (n > 0)
			{
				buffer[n] = 0;
				*out = buffer;
			}

			return n;
		}

		int Send(const std::string &in) override
		{
			int n = send(_sockfd, in.c_str(), in.size(), 0);
			return n;
		}

		int SockFd() override
		{
			return _sockfd;
		}

		int Close() override
		{
			return ::close(_sockfd);
		}

	private:
		int _sockfd;
	};
}